package com.demo.config;

import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: bj910
 * Date:2023-08-07
 * Time: 19:48
 * To change this template use File | Settings | File Templates.
 */

/*
AbstractRoutingDataSource springjdbc提供的抽象的 带路由功能的数据源
相当于是对原始的数据源进行了封装DataSource，为每一个DataSource实例新增一个标签
应用层可以根据切换标签从而达到切换数据源的目的
 */
@Component("dynamicDataSource")
@Primary
public class DynamicDataSource extends AbstractRoutingDataSource {
    public static ThreadLocal<String> name = new ThreadLocal<>();
    @Override
    protected Object determineCurrentLookupKey() {
        //返回key
        return name.get();
    }

    @Resource(name="dataSource1")
    DataSource dataSource1;

    @Resource(name="dataSource2")
    DataSource dataSource2;

    @Override
    public void afterPropertiesSet() {
        Map<Object,Object> map = new HashMap<>();
        //读库
        map.put("R",dataSource1);
        map.put("W",dataSource2);
        super.setTargetDataSources(map);
        super.setDefaultTargetDataSource(dataSource1);
        super.afterPropertiesSet();
    }
}
